<?php

namespace Common\Model;

use Common\Lib\Upload\ImgManager;
use Think\Log;
use Think\Model;

class QuestionImgModel extends Model
{
    /**
     * 获取列表
     *
     * @param string $map
     * @return array
     */
    public function get_list($map = '', $page = false, $sort = '', $num = 10)
    {
        $limit = $num ? $num : 10;

        if (empty($sort)) {
            $sort = 'id DESC';
        }
        if ($page) {
            $count    = $this->where($map)->count();
            $Page     = pager($count, $limit);
            $limit    = $Page->firstRow . ',' . $Page->listRows;
            $page_str = $Page->fshow();
        }

        $list = $this->where($map)->order($sort)->limit($limit)->select();
        foreach ($list as $key => $v) {
//            $v['imgurl'] = $this->img_src($v['img']);
            $list[$key]['imgurl'] = $this->img_src($v['img']);
        }

        $return['list']  = $list;
        $return['count'] = $page ? $count : count($list);
        $return['page']  = $page_str;

        return $return;
    }

    /**
     * 删除图片
     *
     * @param string $ids
     * @return mixed
     */
    public function del_img($ids = '')
    {
        $ids = is_array($ids) ? implode(",", $ids) : $ids;
        if ($ids && preg_match("/^(\d{1,10},)*(\d{1,10})$/", $ids)) {
            $map['id'] = array('IN', $ids);
            $info = $this->get_list($map);
            foreach ($info as $v) {
                if (is_http($v['img'])) {

                } else {
                    $fname = C('YTATA_IMG_QUESTION_DIR') . $v['img'];
                    @unlink($fname);
                }
            }
            $s = $this->delete($ids);
        }
        return $s;
    }

    /**
     * 通过问题ID获取IMG
     *
     * @param string $qid
     * @return array
     */
    public function get_img_qid($qid = '')
    {
        $map['qid'] = intval($qid);
        $img = $this->where($map)->select();
        foreach ($img as $v) {
            $v['imgurl'] = $this->img_src($v['img']);
            $v['thumb_imgurl'] = $this->img_src($v['img'], true);
            $imgs[] = $v;
        }
        return $imgs;
    }

    /**
     * IMG SRC
     *
     * @param string $img
     * @param bool $thumb
     * @return bool|string
     */
    public function img_src($img = '', $thumb = false)
    {
        $img = D('UploadImg')->get_one_id($img);
        $img = new ImgManager($img);
        $url = $img->url();

        if ($thumb) {
            $url = $url . '.thumb.' . substr(strrchr($url, '.'), 1);
        }
        return $url;
    }
}